$(function() {
	preload.setCache(g);
	preload.push('bags', {
		url: g.serviceUrl,
		data: {
			op: 'getBags',
			keyWord: '',
			pageSize: 100000,
			pageIndex: 0
		}
	});
	preload.push('tags', {
		url: g.serviceUrl,
		data: {
			op: 'getTagsForAdmin',
			status: 1,
			pageSize: 100000,
			pageIndex: 0
		}
	});
	preload.run(start);
});


// 定义全局变量
var tagsPickerNode;
var tagsAutoNode;
var bagsAccoNode;
var tagsPackageNode;
var videoListNode;
var searBtnNode;

var pagerNode;

function start() {
	setNode();
	create();
	first();

	function setNode() {
		tagsPickerNode = $('#tagsPicker');
		tagsAutoNode = $('#tagsAuto');
		bagsAccoNode = $('#bagsAcco');

		tagsPackageNode = $('#tagsPackage');
		searBtnNode = $('#searBtn');
		clearBtnNode = $('#clearBtn');

		videoListNode = $('#videoList');

		pagerNode = $('#pager');
		pagerNode.leftBtn = $('#pager-left');
		pagerNode.rigthBtn = $('#pager-right');
		pagerNode.total = $('#pager-total');
	}


	function create() {

		//createTooltip();
		createTagsPicker();

		createTagsPackage();

		createTagsBtn();

		function createTooltip() {
			$(document).tooltip({
				open: function(e, ui) {
					if(!ui.tooltip.data('isFirst')) {
						//ui.tooltip('disable');
						//ui.tooltip('destroy');
						return false;
					}
					ui.tooltip.data('isFirst', 1);
				}
			});

		}

		function createTagsPicker() {
			tagsPickerNode.tabs();

			// autoComplete
			createTagsAuto();

			createBagsAcco();

			createVideoList();

			function createTagsAuto() {
				tagsAutoNode.autocomplete({
					source: formatter(g.tags)
				});
				tagsAutoNode.keyup(function(e) {
					if(e.keyCode == 13) {
						var tagName = tagsAutoNode.val();
						if(checker.tag(tagName)) {
							director.setTag(tagName, 1);
							params.setTag(tagName, 1)
						}
					}
				});

				var tagsBtnNode = $('#tagsBtn');
				tagsBtnNode.button({
					icons: {
						primary: "ui-icon-plus"
					},
					text: false
				});
				tagsBtnNode.click(function(e) {
					var tagName = tagsAutoNode.val();
					if(checker.tag(tagName)) {
						director.setTag(tagName, 1);
						params.setTag(tagName, 1)
					}
				});

				function formatter(data) {
					var rst = [];
					$.each(data.data[0], function(i, n) {
						rst.push(n.name);
					});
					log(rst);
					return rst;
				}
			}

			function createBagsAcco() {
				var data = formatter(g.bags.data[0], g.tags.data[0]);
				var h3Node = $('<h3/>');
				var divNode = $('<div/>');

				$.each(data, function(i, n) {
					bagsAccoNode.append(h3Node.clone().text(n.name));
					var dc = divNode.clone();
					bagsAccoNode.append(dc);
					$.each(n.tags, function(ii, nn) {

						dc.append(divNode.clone().addClass('tagItem').text(nn).draggable({
							//revert: true,
							helper: "clone",
							stop: function(e, ui) {
								//log(e, ui);
							}
						}));
					});
				});

				bagsAccoNode.find('div.tagItem').live('click', function(e) {
					var tagName = $(this).text();
					if(checker.tag(tagName)) {
						director.setTag(tagName, 1);
						params.setTag(tagName, 1);
					}
				});

				bagsAccoNode.accordion({
					collapsible: true
				});

				function formatter(bags, tags) {
					var rst = [];
					$.each(bags, function(i, n) {
						var item = {};
						item.name = n.name;
						item.tags = [];
						$.each(tags, function(ii, nn) {
							if(nn.bagId == n.id) {
								item.tags.push(nn.name);
							}
						});
						rst.push(item);
					});
					log(rst);
					return rst;
				}

			}

		}

		function createTagsPackage() {

			tagsPackageNode.tabs({
				active: 0,
				collapsible: true
			});

			tagsPackageNode.find('.main').droppable({
				accept: '.tagItem',
				drop: function(e, ui) {
					var tagName = ui.draggable.text();

					if(checker.tag(tagName)) {
						// display
						director.setTag(tagName, 1);
						// data
						params.setTag(tagName, 1);
					}
					log(ui);
				}
			});



			tagsPackageNode.find('.main [ptag="tagItem"]').live('click', function(e) {
				var tagName = $(this).text();
				if(!checker.tag(tagName)) {
					// display
					director.setTag(tagName, 0);
					// data
					params.setTag(tagName, 0);
				}


			});


		}

		function createTagsBtn() {
			/// sear
			searBtnNode.button({
				icons: {
					secondary: "ui-icon-search"
				}
			});
			searBtnNode.click(function(e) {
				var opts = {
					tagIds: params.getTag().join(','),
					pageIndex: 0,
					pageSize: 8
				};
				var callback = function(data) {
						director.setVideoList(data[0], $('.mainForSearch'));

					};
				dataManager.getVideoData(opts, callback);
			});

			/// clear
			clearBtnNode.button({
				icons: {
					secondary: "ui-icon-close"
				}
			});
			clearBtnNode.click(function(e) {
				var tagItems = tagsPackageNode.find('.main [ptag="tagItem"]');
				$.each(tagItems, function(i, n) {
					var tagName = $(n).button('option').label;
					director.setTag(tagName, 0);
					params.setTag(tagName, 0);
				})
			});

		}

		function createVideoList() {
			videoListNode.tabs({
				active: 1,
				collapsible: true
			});

			// init pager
			createPager();

			function createPager() {
				pagerNode.leftBtn.button({
					icons: {
						primary: 'ui-icon-triangle-1-w'
					},
					text: false
				}).click(function() {
					director.pager(g.video, 'left');
				});
				pagerNode.rigthBtn.button({
					icons: {
						primary: 'ui-icon-triangle-1-e'
					},
					text: false
				}).click(function() {
					director.pager(g.video, 'right');
				});
			}
		}

	}

	function first() {}

}

var checker = {
	tag: function(tagName) {
		var tp = g.tagsPackage;
		var tag = JSLINQ(g.tags.data[0]).First(function(c) {
			return c.name == tagName;
		});
		return tag != null && $.inArray(tag.name, tp) == -1;
	}
};

var director = {
	setTag: function(tagName, type) {
		if(type == 1) {
			var itemNode = $('<button ptag="tagItem" />').text(tagName);
			tagsPackageNode.find('.main').append(itemNode);
			itemNode.button();
		} else {
			var itemNode = tagsPackageNode.find(':button:contains(' + tagName + ')');
			itemNode.remove();

		}
	},
	setVideoList: function(videoDataList, parentNode) {
		var divNode = $('#template .videoItem').clone();
		$.each(videoDataList, function(i, n) {
			var node = divNode.clone();
			var video = n.video;
			var tags = n.tags;
			node.find('.rowId').text(i + 1);
			node.find('.name').find('a').text(video.name).attr('href',video.url);
			_createVideoItemCount(node.find('.count'), video.count);
			node.find('.dt').text(formatter(video.dt));
			_createVideoItemTag(node, tags);
			parentNode.append(node);

		});

		function _createVideoItemCount(parentNode, count) {
			var num = -1;
			var className = '.ui-icon-lightbulb';
			var baseCount = 40;
			num = parseInt(count / baseCount);
			num > 5 && (num = 5);
			num == 0 && (num = 1);

			var node = $('#template .videoItemCountIcon').clone();
			for(var i = num - 1; i >= 0; i--) {
				parentNode.append(node);
			};
		}

		function _createVideoItemTag(node, tags) {
			node.attr('title', JSLINQ(tags).Select(function(c) {
				return c.name;
			}).Select(function(c) {
				return '[' + c + ']';
			}).ToArray().join(','));


		}

		function formatter(dt) {
			var str = dt.match(/\d+/g)[0];
			var time = new Date(str - 0);
			return time.toString('yyyy-MM-dd');
		}

	},
	setVideo: function(video, type) {
		if(type == 1) {

		} else {}
	},
	setVideoPager: function(data) {
		//pageIndex,pageSize ,total
	},
	setVideoPageIndex: function(pageIndex) {}
};

var params = {
	setTag: function(tagName, type) {
		if(type == 0) {
			$.each(g.tagsPackage, function(i, n) {
				if(n == tagName) {
					g.tagsPackage.splice(i, 1);
					return false;
				}
			});

		} else {
			g.tagsPackage.push(tagName);
		}
	},
	getTag: function() {
		var rst = [];
		$.each(g.tagsPackage, function(i, n) {
			var tag = JSLINQ(g.tags.data[0]).First(function(c) {
				return c.name == n;
			});
			rst.push(tag.id);
		});
		return rst;
	}
};

// 全局变量 
// 数据缓存
var g = {
	//dgData
	serviceUrl: '../service/tagerOp.ashx',
	tagsPackage: []
};


// 数据接口
var dataManager = {
	getVideoData: function(opts, next) {
		var url = g.serviceUrl;
		var data = $.extend({
			op: 'search'
		}, opts);
		var callback = function(data) {
				if(data.flag) {
					next(data.data);
				}
			};
		$.post(url, data, callback);
	}
};

function log(obj) {
	window.console && console.log(obj);
}